from dict_db import *
from multiprocessing import Process
from socket import *
mysql={
      "host":"localhost",
      "port":3306,
      "user":"root",
      "passwd":"123456",
      "database":"dict",
      "charset":"utf8"
}

db=SqlLink(mysql)
class DictServer():
    def __init__(self,host="0.0.0.0",port=65535):
        self.host=host
        self.port=port
        self.ADDR=(host,port)
        self.sock=self._create_sock()


    def _create_sock(self):
        sock=socket()
        sock.bind(self.ADDR)
        return sock

    # def link_client(self):
    #     self.sock.listen(5)
    #     print("Listen port 8888")
    #     conne, addr = self.sock.accept()
    #     print("Connect form:", addr)
    #     return conne,addr

    def dispose(self,conne,addr):
        while True:
            info=conne.recv(1024).decode()
            if not info or info == "退出":
                break
            data=info.split("**&&^^")
            if data[0] == "LOGIN":
                if self.login(data):
                    conne.send(b"ok")
                else:
                    conne.send(b"bad")

            if data[0] == "REGISTER":
                info=self.register(data)
                conne.send(info.encode())

            if data[0] == "INQUERE":
                info=self.inquere(data)
                conne.send(info.encode())


            if data[0] == "HISTORY":
                info=self.history(data)
                conne.send(info.encode())

    def main(self):
        self.sock.listen(5)
        print("Listen port 8888")
        while True:
            conne, addr = self.sock.accept()
            print("Connect form:", addr)
            p=Process(target=self.dispose,kwargs={"conne": conne, "addr": addr})
            p.start()

    def login(self,client_data):
        return db.inquere_user(name=client_data[1], passwd=client_data[2])

    def register(self,client_data):
        return db.insert(name=client_data[1], passwd=client_data[2])

    def inquere(self,client_data):
        return db.inquere(client_data[1],client_data[2])

    def history(self,client_data):
        history_info_start=db.inquere_history(user_name=client_data[1])
        if not history_info_start:
            return "还没有记录"
        history_info = "名字  单词     查询时间\n"
        for item in history_info_start:
            history_info += "  %s  %s  %s\n"%item
        return history_info



if __name__=="__main__":
    di=DictServer(host="0.0.0.0",port=8888)
    di.main()